import { useEffect, useState } from "react";
import { useBearStore } from "../stores/bearStore";
import { useFoodStore } from "../stores/foodStore";
import { shallow } from "zustand/shallow";

export const BearBox = () => {
  // const bears = useBearStore(state => state.bears)
  // const increasePopulation = useBearStore(state => state.increasePopulation)
  // const removeAllBears = useBearStore(state => state.removeAllBears)

  const { bears, increasePopulation, removeAllBears } = useBearStore();
  // const fish = useFoodStore(state => state.fish) // 会导致BearBox重渲染

  const [bgColor, setBgColor] = useState(useBearStore.getState(state => state.fish) > 5 ? "lightgreen" : "lightpink");
  useEffect(() => {
    // const unsub = useFoodStore.subscribe((state, prevState) => {
    //     if(prevState.fish <= 5 && state.fish > 5) {
    //         setBgColor("lightgreen")
    //     } else if(prevState.fish > 5 && state.fish <=5) {
    //         setBgColor("lightpink")
    //     }
    // })

    const unsub = useFoodStore.subscribe(
      (state) => state.fish,
      (fish, prevFish) => {
        if (prevFish === fish) {
          // 当不立马执行的情况（fireImmediately: false）下，useFoodStore.subscribe第一次调用则不会进入这里
          if (fish < 5) setBgColor("lightpink");
          else setBgColor("lightgreen");
        }
        if (prevFish <= 5 && fish > 5) {
          setBgColor("lightgreen");
        } else if (prevFish > 5 && fish <= 5) {
          setBgColor("lightpink");
        }
      },
      {
        equalityFn: shallow, // 两个值比较
        fireImmediately: true, // 是否调用时就立马执行， 默认是false
      }
    );
    return unsub;
  }, []);
  return (
    <div className="box" style={{ backgroundColor: bgColor }}>
      <h1>Bear Box</h1>
      <p>bears: {bears}</p>
      <p>测试重渲染：{Math.random()}</p>
      <div>
        <button onClick={increasePopulation}>add bear</button>
        <button onClick={removeAllBears}>remove bear</button>
        <button onClick={useBearStore.persist.clearStorage}>
          clear storage
        </button>
      </div>
    </div>
  );
};
